<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select
          v-model="queryParams.auditStatus"
          placeholder="审核状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in auditStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="batchImport"
        >批量导入</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="tableList">
      <el-table-column label="文档Id" prop="id" />
      <el-table-column label="文档名称" prop="fileName" />
      <el-table-column label="文档状态">
        <template slot-scope="scope">
          <i v-if="scope.row.fileStatus === 1" class="el-icon-success" style="color: #52c41a"></i>
          <i v-else-if="scope.row.fileStatus === 0" class="el-icon-loading" style="color: #07a7ec"></i>
          <i v-else class="el-icon-error" style="color: #f51a2d"></i>
          <span :class="scope.row.fileStatus === 0 ? 'status-text-info': scope.row.fileStatus === 1 ? 'status-text':'status-text-fail'">
            {{ scope.row.fileStatus === 0 ? '解析中' :  scope.row.fileStatus === 1 ? '解析成功' : '解析失败' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件大小">
        <template slot-scope="scope">
          {{ formatBytes(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column label="解析日期" prop="createTime"/>
      <el-table-column label="生成问答对数量 key" prop="qnaNum"/>
      <el-table-column label="问答对状态">
        <template slot-scope="scope">
          <span>{{ scope.row.auditStatus === 1 ? '已审核' : '未审核' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联知识库" prop="kbId"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-paperclip"
            @click="openDetails(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="批量导入"
      :visible.sync="dialogVisible"
      width="30%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="width: 90%;margin-left: 5%">
        <el-form-item label="大模型" prop="llm_id">
          <el-select v-model="form.llm_id" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="知识库" prop="kb_id">
          <el-select v-model="form.kb_id" placeholder="请选择">
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="upload-container">
        <!-- 拖拽上传区域 -->
        <el-upload
          ref="uploadRef"
          class="upload-dragger"
          style="margin-top: 15px"
          drag
          :action="uploadFaqUrl"
          :headers="uploadHeaders"
          :data="{llm_id:form.llm_id,kb_id:form.kb_id}"
          :file-list="fileList"
          :multiple="false"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="upload-tip">
            <p>支持文件格式：md, txt, docx</p>
          </div>
        </el-upload>
      </div>
    </el-dialog>
    <el-dialog
      title="问答对详情"
      :visible.sync="detailsVisible"
      width="50%">

      <el-table v-loading="loading" :data="detailsTableList" height="500px">
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column label="问题" prop="question" />
        <el-table-column label="答案" prop="answer" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="editQna(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              style="color: red"
              @click="delQna(scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="passQna(scope.row)"
            >审核通过</el-button>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
            <el-button @click="detailsVisible = false">取消</el-button>
            <el-button type="primary" @click="detailsVisible = false">确 定</el-button>
          </span>
    </el-dialog>

    <el-dialog
      title="问答对修改"
      :visible.sync="qnaVisible"
      width="30%">
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="60px" style="width: 90%;margin-left: 5%">
        <el-form-item label="问题" prop="question">
          <el-input
            v-model="form2.question"
            placeholder="请输入问题，100字符以内"
            maxlength="100"
            show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input
            v-model="form2.answer"
            type="textarea"
            :rows="5"
            maxlength="1000"
            show-word-limit
            placeholder="请输入答案，1000字符以内">
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
            <el-button @click="qnaVisible = false">取消</el-button>
            <el-button type="primary" @click="handelEdit">确 定</el-button>
          </span>
    </el-dialog>
  </div>
</template>

<script>
import { qnaTaskList,cQnaList,updateQna,deleQna,addFaq } from '@/api/createQna/index'
import { createQnaList } from '@/api/createQna/index'
import { list } from '@/api/knowledgemanagement/index'

export default {
  data() {
    return {
      loading: true,
      total: 0,
      title: "",
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: undefined,
        auditStatus: undefined
      },
      tableList:[],
      form:{
        llm_id:'',
        kb_id:'',
      },
      rules: {
        llm_id: [
          { required: true, message: '请选择大模型', trigger: 'blur' }
        ],
        kb_id: [
          { required: true, message: '请选择知识库', trigger: 'blur' }
        ],
      },
      auditStatusOptions:[{text:0,value:0},{text:1,value:1}],
      dialogVisible: false,
      activeName: '问答对审核通过',
      uploadHeaders: {
        'Authorization': ""
      },
      uploadFaqUrl: process.env.VUE_APP_BASE_API + '/createQna/uploadDoc', // 后端上传接口
      allowedTypes: ['md','txt','docx'], // 允许的文件类型
      fileList:[],
      options:[],
      options2:[],
      detailsVisible: false,
      taskId:'',
      detailsTableList:[],
      qnaVisible: false,
      form2:{
        id:'',
        question:'',
        answer:'',
      },
      rules2: {
        question: [
          { required: true, message: '请输入问题', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入问题答案', trigger: 'blur' }
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取认证令牌（从Cookie中）
    getAuthToken() {
      const token = this.getCookie('Admin-Token'); // 键名与Cookie名称一致
      return token ? `Bearer ${token}` : ''; // 拼接Bearer前缀
    },
    getCookie(name) {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        // 查找以目标名称开头的Cookie（格式："name=value"）
        if (cookie.startsWith(`${name}=`)) {
          return cookie.substring(name.length + 1); // 返回值部分
        }
      }
      return null; // 未找到返回null
    },
    getList() {
      this.loading = true;
      qnaTaskList(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
        this.tableList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleTabClick() {

    },
    beforeUpload(file) {
      // 1. 验证文件类型
      const fileExt = file.name.split('.').pop().toLowerCase();
      if (!this.allowedTypes.includes(fileExt)) {
        this.$message.error(`不支持的文件格式: ${fileExt}，请下载模板后填写上传`);
        return false;
      }

      if(this.form.llm_id == null || this.form.llm_id == ''){
        this.$message.error(`请选择一个大模型配置`);
        return false;
      }

      if(this.form.kb_id == null || this.form.kb_id == ''){
        this.$message.error(`请选择一个知识库`);
        return false;
      }

      return true
    },
    handleUploadSuccess(response, file, fileList) {
      // 检查是否所有文件都上传完成
      const allSuccess = fileList.every(item => item.status === 'success');
      if (allSuccess) {
        this.$message.success('所有文件上传成功');
        this.dialogVisible = false;
        this.fileList = []
        this.resetQuery();

        setTimeout(() => {
          this.resetQuery(); // 重新加载列表
        }, 5000);

        setTimeout(() => {
          this.resetQuery(); // 重新加载列表
        }, 15000);
      }
    },
    batchImport(){
      this.dialogVisible = true
      this.options = []
      this.options2 = []
      // 从Cookie中获取Admin-Token并设置请求头
      const token = this.getAuthToken();
      if (!token) {
        this.$message.error('未找到登录令牌，请重新登录');
        return;
      }

      this.uploadHeaders.Authorization = token; // 更新请求头
      createQnaList({configName: undefined}).then(res => {
        res.data.forEach(row => {
          this.options.push({label:row.configName,value:row.id})
        })
        list().then(res2 => {
          res2.data.forEach(row => {
            this.options2.push({label:row.kb_name,value:row.kb_id})
          })
        })
      })
    },
    openDetails(row){
      this.detailsVisible =true
      this.taskId = row.taskId
      this.getQnaDetailsList()
    },
    getQnaDetailsList(){
      cQnaList({taskId:this.taskId}).then(res => {
        this.detailsTableList = res.data
      })
    },
    formatBytes(bytes){
      if(bytes <= 1024*1024){
        return (bytes/1024).toFixed(2) + 'KB'
      }else{
        return (bytes/(1024*1024)).toFixed(2) + 'MB'
      }
    },
    editQna(row){
      this.qnaVisible = true
      this.form2 = Object.assign({},row)
    },
    handelEdit(){
      this.$refs.form2.validate(valid => {
        if (valid) {
          updateQna({
            "id": this.form2.id,
            "question": this.form2.question,
            "answer": this.form2.answer
          }).then(res => {
            this.$message.success('修改成功');
            this.qnaVisible = false
            this.getQnaDetailsList()
          })
        }
      })
    },
    delQna(row){
      updateQna({
        "id": row.id
      }).then(res => {
        this.$message.success('删除成功');
        this.getQnaDetailsList()
      })
    },
    passQna(row){
      addFaq({
        "id": row.id,
        "question": row.question,
        "answer": row.answer
      }).then(res => {
        this.$message.success('审核通过');
        this.getQnaDetailsList()
      })
    }
  }
};
</script>

<style lang='scss' scoped>
.status-text {
  font-size: 12px;
  color: #52c41a;
}

.status-text-info {
  font-size: 12px;
  color: #07a7ec;
}

.status-text-fail {
  font-size: 12px;
  color: #f51a2d;
}
</style>
